﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace WebShopData
{
    public class DBException : Exception
    {
        private Exception _innerException;
        public int ExceptionID { get; set; }
        public string ExceptionMessage { get; set; }
        public new Exception InnerException { get { return _innerException; } }
        public string ExceptionType { get; set; }

        public DBException(string exceptionMessage, Exception innerException, int exceptionID = 0)
        {
            ExceptionID = exceptionID;
            ExceptionMessage = exceptionMessage;
            _innerException = innerException;
        }

        public DBException(string exceptionMessage, string exceptionType)
        {
            ExceptionMessage = exceptionMessage;
            ExceptionType = exceptionType;
        }


        public void Load(SqlDataReader reader)
        {
            ExceptionID = int.Parse(reader["ExceptionID"].ToString());
            ExceptionMessage = reader["ExceptionMessage"].ToString();
        }

        public static int AddException(string message, string exceptionType)
        {
            try
            {
                using (SqlConnection connection = DB.GetConnection())
                {
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = string.Format(@"EXEC AddExceptions '{0}', '{1}'", message, exceptionType);

                        var dataset = new DataSet();
                        int affectedrows = new SqlDataAdapter(command).Fill(dataset);
                        return affectedrows;
                    }
                }
            }

            catch (Exception e)
            {
                DBException.AddException(e.Message, e.GetType().ToString());
                throw new Exception();
            }
        }

        public override string ToString()
        {
            return string.Format("ExceptionID:{0} Exceptionmessage:{1} Exceptiontype:{2}", ExceptionID, ExceptionMessage, InnerException.InnerException);
        }
    }

}

